<?php
session_start();
require_once("Structure/fonctions.php");

$PAGE_TITLE = "Connexion - Lolgames";
$CONTENT_INCLUDE = "connexion.html";

if(!isset($_SESSION["user_id"])) {

    if(isset($_POST["valider"])) {
        $login = $_POST["login"];
        $password = sha1($_POST["password"]);

        $bdd = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_BASE);

        // On cherche un user avec cette combinaison de login/pwd
        $query = "SELECT  * FROM users
                  WHERE   pseudo = '".$login."' AND password = '".$password."'
                    OR    email = '".$login."'  AND password = '".$password."' ;";
        $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

        if(mysqli_num_rows($res) == 1) {
            $row = mysqli_fetch_array($res);

            if($row["statusID"] == 19) {
                $error = "Vous êtes banni !";
            }
            else {
                $_SESSION["user_id"] = $row["id"];

				if ($_POST['connexion_auto'] = true)
				{
					setcookie('pseudo', $login, time() + 1*3600, null, null, false, true);
					setcookie('password', $password, time() + 1*3600, null, null, false, true);
				}
				else
				{
					setcookie('pseudo', $login, time() + 1*900, null, null, false, true);
					setcookie('password', $password, time() + 1*900, null, null, false, true);
				}

                // on exclu ces pages de la redirection
                $exclusion[0] = WEBROOT."inscription.php";
                $exclusion[1] = WEBROOT."connexion.php";

                if (isset($_POST["redirect"]) &&
                    in_array($_POST["redirect"], $exclusion) == 0) {
                    header("Location: ".$_POST["redirect"]);
                    exit;
                }
                else {
                    header("Location: index.php");
                    exit;
                }
            }
        }

        if(mysqli_num_rows($res) == 0) {
            $error = "Le login et le mot de passe ne correspondent pas !";
        }
    }
}
else {
    if(isset($_POST["disconnect"])) {
        session_unset();
        session_destroy();

        header("Location: index.php");
        exit;
    }
}

include_once ("Structure/structure.php");

?>